package com.cskaoyan.gateway.controller.pay;

import com.cskaoyan.gateway.form.pay.PayForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Author: JK
 * @Date: create in 2021/7/26 15:58
 */
@Slf4j
@RestController
@RequestMapping("cashier")
public class PayController {
    @Value("${server.address}")
    String serverAddress;

    @Value("${server.port}")
    String serverPort;

    @Reference(timeout = 30000, check = false, retries = 0)
    PayCoreService payCoreService;

    @PostMapping("pay")
    public ResponseData prePay(@RequestBody PayForm payForm, HttpServletRequest servletRequest){
        log.info("支付表单数据：{}", payForm);
        PaymentRequest paymentRequest = new PaymentRequest();
        String uid = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);

        paymentRequest.setUserId(Long.parseLong(uid));
        paymentRequest.setUsername(payForm.getNickName());
        paymentRequest.setOrderId(payForm.getOrderId());
        paymentRequest.setTotalFee(payForm.getMoney());
        paymentRequest.setOrderFee(payForm.getMoney());
        paymentRequest.setSubject(payForm.getInfo());
        paymentRequest.setSpbillCreateIp(servletRequest.getRemoteAddr());
        paymentRequest.setPayChannel(payForm.getPayType());
        // tradeNo，在获取到支付二维码时填入
        // addressId不写
        //paymentRequest.setAddressId();

        AlipaymentResponse response = payCoreService.aliPay(paymentRequest);

        if (PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())) {
            String qrCode = response.getQrCode();
            String codeUrl = "http://" + serverAddress + ":" + serverPort + "/image/" + qrCode;
            return new ResponseUtil<>().setData(codeUrl);
        }

        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @GetMapping("queryStatus")
    public ResponseData queryPayStatus(String orderId) {
        PaymentRequest paymentRequest = new PaymentRequest();

        paymentRequest.setOrderId(orderId);
        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(paymentRequest);
        if (PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(null);
        }

        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
